package logic

import (
	"context"
	"errors"
	"user-goods-hub/models/cache"
	"user-goods-hub/models/mysql"
	"user-goods-hub/pkg"

	"user-goods-hub/userrpc/internal/svc"
	"user-goods-hub/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	user := mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	if len(in.Password) < 8 {
		return nil, errors.New("密码长度过短且包含大小写字母+数字+特殊符号，请重新设置")
	}
	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, errors.New("注册失败")
	}
	if user.Password != in.Password {
		return nil, errors.New("密码不正确")
	}
	Captcha, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if Captcha != in.Captcha {
		return nil, errors.New("图形验证码不正确")
	}

	result, _ := cache.Rdb.Get(l.ctx, "mobile"+in.Mobile).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误")
	}

	return &userrpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
